<template>
    <div class="lifecycle-page-container">
        <!-- 1. 功能说明区域 -->
        <div class="page-header-description">
            <p>
                您可以基于最后一次修改时间 (Last Modified Time) 配置生命周期规则，
                定期将存储桶 (Bucket) 内过期的文件、历史版本或文件碎片进行删除，
                从而实现自动化数据清理，有效节省存储费用。
            </p>
            <el-alert title="生命周期规则配置和修改后将在48小时内生效。（生命周期列表的展示有延迟，将在设置成功1分钟内更新。）" type="info" show-icon
                :closable="false" />
        </div>

        <!-- 2. 操作栏 -->
        <div class="action-bar">
            <el-button type="primary" @click="handleOpenDrawer(null)">创建规则</el-button>
            <el-button @click="fetchLifecycleRules" :loading="loading">刷新</el-button>
        </div>

        <!-- 3. 规则列表 -->
        <el-table :data="rules" v-loading="loading" style="width: 100%">
            <el-table-column prop="ID" label="规则名称" />
            <el-table-column label="状态" width="100">
                <template #default="{ row }">
                    <el-tag :type="row.Status === 'Enabled' ? 'success' : 'info'">
                        {{ row.Status === 'Enabled' ? '启用中' : '已禁用' }}
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column label="应用范围">
                <template #default="{ row }">
                    {{ row.Filter.Prefix || '整个存储桶' }}
                </template>
            </el-table-column>
            <el-table-column label="过期规则描述" width="400">
                <template #default="{ row }">
                    <div v-if="row.Expiration">
                        当前版本在 {{ row.Expiration.Days }} 天后过期
                    </div>
                    <div v-if="row.NoncurrentVersionExpiration">
                        历史版本在 {{ row.NoncurrentVersionExpiration.NoncurrentDays }} 天后永久删除
                    </div>
                    <div v-if="row.AbortIncompleteMultipartUpload">
                        碎片在启动 {{ row.AbortIncompleteMultipartUpload.DaysAfterInitiation }} 天后自动删除
                    </div>
                </template>
            </el-table-column>
            <el-table-column label="操作" width="150">
                <template #default="{ row }">
                    <el-button link type="primary" @click="handleOpenDrawer(row)">编辑</el-button>
                    <el-button link type="danger" @click="handleDeleteRule(row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- 4. 创建/编辑规则的抽屉 -->
        <LifecycleRuleDrawer v-if="drawerVisible" :visible="drawerVisible" :bucket-name="bucketName"
            :is-versioning-enabled="isVersioningEnabled" :rule-to-edit="ruleToEdit" @close="drawerVisible = false"
            @success="handleSuccess" />
    </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import apiClient from '@/api';
import { ElMessage, ElMessageBox } from 'element-plus';
import LifecycleRuleDrawer from './LifecycleRuleDrawer.vue'; // 引入抽屉组件

const props = defineProps({
    bucketName: {
        type: String,
        required: true,
    },
});

const rules = ref([]);
const loading = ref(false);
const drawerVisible = ref(false);
const ruleToEdit = ref(null);
const isVersioningEnabled = ref(false);

const fetchBucketVersioning = async () => {
    try {
        const response = await apiClient.get(`/api/v1/buckets/${props.bucketName}/details`);
        isVersioningEnabled.value = response.data.versioning === '已开启';
    } catch (error) {
        console.error('获取版本状态失败:', error);
        ElMessage.error('获取存储桶版本状态失败');
    }
};

const fetchLifecycleRules = async () => {
    loading.value = true;
    try {
        const response = await apiClient.get(
            `/api/v1/buckets/${props.bucketName}/lifecycle`
        );
        rules.value = response.data;
    } catch (error) {
        console.error('获取生命周期规则失败:', error);
        ElMessage.error('获取生命周期规则失败');
    } finally {
        loading.value = false;
    }
};

const handleOpenDrawer = (rule) => {
    ruleToEdit.value = rule ? { ...rule } : null; // 传递副本以避免直接修改列表数据
    drawerVisible.value = true;
};

const handleDeleteRule = async (ruleToDelete) => {
    try {
        await ElMessageBox.confirm(
            `确定要删除规则 “${ruleToDelete.ID}” 吗？此操作不可恢复。`,
            '删除确认',
            {
                confirmButtonText: '确定删除',
                cancelButtonText: '取消',
                type: 'warning',
            }
        );

        loading.value = true;
        const updatedRules = rules.value.filter(r => r.ID !== ruleToDelete.ID);

        // 调用PUT接口，用新的规则列表覆盖
        await apiClient.put(`/api/v1/buckets/${props.bucketName}/lifecycle`, { rules: updatedRules });

        ElMessage.success('规则删除成功');
        fetchLifecycleRules(); // 重新获取列表

    } catch (error) {
        if (error !== 'cancel') {
            console.error('删除规则失败:', error);
            ElMessage.error(error.response?.data?.error || '删除规则失败');
        }
    } finally {
        loading.value = false;
    }
};

const handleSuccess = () => {
    drawerVisible.value = false;
    fetchLifecycleRules();
};

onMounted(() => {
    fetchBucketVersioning();
    fetchLifecycleRules();
});
</script>

<style scoped>
.lifecycle-page-container {
    padding: 20px;
}

.page-header-description {
    margin-bottom: 20px;
    background-color: #f4f4f5;
    padding: 15px;
    border-radius: 4px;
}

.page-header-description p {
    margin-top: 0;
}

.action-bar {
    margin-bottom: 20px;
}
</style>